﻿namespace EyeOpen.Mapping.Validation
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Xml.Linq;

    public class ValidationMapper : BaseMapper
    {
        private IDictionary<Type, IList<Validator>> validators;

        public ValidationMapper() 
        {
        }
        
        public ValidationMapper(IDictionary<Type, IList<Validator>> validators)
            : base()
        {
            this.validators = validators;
        }        

        public override IDictionary<Type, XElement> GenerateMappings(Assembly assembly)
        {
            return base.GenerateMappings(assembly, type => (!type.IsAbstract));
        }

        public override XElement GenerateMappings(Type type)
        {
            XElement validableEntityElement = new XElement("validableEntity");
            validableEntityElement.SetAttributeValue("name", type.FullName);

            PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);

            properties
                .Where(property => IsBaseType(property.PropertyType))
                .ToList()
                .ForEach(property => this.AddProperty(validableEntityElement, property));
            return validableEntityElement;
        }

        private void AddProperty(XElement validableEntityElement, PropertyInfo property)
        {
            XElement propertyElement = new XElement("property");
            propertyElement.SetAttributeValue("name", property.Name);
            propertyElement.SetAttributeValue("type", property.PropertyType.FullName);

            if (this.validators.ContainsKey(property.PropertyType))
            {
                foreach (KeyValuePair<Type, IList<Validator>> keyValue in this.validators)
                {
                    foreach (Validator validator in keyValue.Value)
                    {
                        XElement validatorElement = new XElement("validator");
                        validatorElement.SetAttributeValue("name", validator.Name);
                        if (validator.Parameters != null)
                        {
                            foreach (KeyValuePair<string, object> parameter in validator.Parameters)
                            {
                                validatorElement.SetAttributeValue(parameter.Key, parameter.Value.ToString());
                            }
                        }

                        propertyElement.Add(validatorElement);
                    }
                }
            }

            validableEntityElement.Add(propertyElement);
        }
    }
}
